package utils

import (
	"os"
	"io"
	"github.com/tebeka/selenium"
	"image"
	"bytes"
	"path/filepath"
	"image/jpeg"
	"image/png"
	"errors"
	"strings"
	"image/gif"
	"fmt"
	"encoding/base64"
)

// 是否存在该文件
func Exist(filename string) bool {
	_, err := os.Stat(filename)
	return err == nil || os.IsExist(err)
}

// 获取临时img图片路径
func GetTempImgPath() string {
	path, _ := os.Getwd()
	return path + "/temp.jpg"
}

// 获取临时html路径
func GetTempPagePath() string {
	path, _ := os.Getwd()
	return path + "/temp.html"
}

// 拷贝文件
func CopyFile(dstName, srcName string) (written int64, err error) {
	src, err := os.Open(srcName)
	if err != nil {
		return
	}
	defer src.Close()
	dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		return
	}
	defer dst.Close()
	return io.Copy(dst, src)
}

// 截取图片
func Screenshot(imgBytes []byte, size *selenium.Size, point *selenium.Point, dpiRate int) (string) {
	imgPath := GetTempImgPath()
	os.Remove(imgPath)
	fd, _ := os.OpenFile(imgPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	fd.Write(imgBytes)
	//截图
	srcImg, s, _ := image.Decode(bytes.NewReader(imgBytes))
	fmt.Println(s, point.X, point.Y, size.Width, size.Height)
	dstImg, err := ImageCopy(srcImg, point.X*dpiRate, point.Y*dpiRate, size.Width*dpiRate, size.Height*dpiRate)
	if err != nil {
	}
	buf := new(bytes.Buffer)
	err = jpeg.Encode(buf, dstImg, nil)
	if err != nil {
	}
	base64img := base64.StdEncoding.EncodeToString(buf.Bytes())

	imgPath2 := strings.Replace(imgPath, "temp", "temp2", 1)
	SaveImage(imgPath2, dstImg)

	return base64img
}

func ImageCopy(src image.Image, x, y, w, h int) (image.Image, error) {
	var subImg image.Image

	if rgbImg, ok := src.(*image.YCbCr); ok {
		subImg = rgbImg.SubImage(image.Rect(x, y, x+w, y+h)).(*image.YCbCr) //图片裁剪x0 y0 x1 y1
	} else if rgbImg, ok := src.(*image.RGBA); ok {
		subImg = rgbImg.SubImage(image.Rect(x, y, x+w, y+h)).(*image.RGBA) //图片裁剪x0 y0 x1 y1
	} else if rgbImg, ok := src.(*image.NRGBA); ok {
		subImg = rgbImg.SubImage(image.Rect(x, y, x+w, y+h)).(*image.NRGBA) //图片裁剪x0 y0 x1 y1
	} else {

		return subImg, errors.New("图片解码失败")
	}
	return subImg, nil
}

func SaveImage(dstPath string, src image.Image) error {
	os.Remove(dstPath)
	f, err := os.OpenFile(dstPath, os.O_SYNC|os.O_RDWR|os.O_CREATE, 0666)

	if err != nil {
		return err
	}
	defer f.Close()
	ext := filepath.Ext(dstPath)

	if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") {

		err = jpeg.Encode(f, src, &jpeg.Options{Quality: 80})

	} else if strings.EqualFold(ext, ".png") {
		err = png.Encode(f, src)
	} else if strings.EqualFold(ext, ".gif") {
		err = gif.Encode(f, src, &gif.Options{NumColors: 256})
	}
	return err
}
